package com.hongtai.common.util;

import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.Properties;

/**
 * 配置文件加载类
 */
public class PropertiesLoader {

    /**
     * 加载固定路径的配置文件
     * @param filePath
     * @return
     * @throws IOException
     */
    public static Properties loadPropertiesByFilePath(String filePath) throws IOException {
        InputStream is = new FileInputStream(new File(filePath));
        return  loadProperties(is);
    }


    /**
     * 加载class的根路径下的配置文件
     * @param fileName
     * @return
     * @throws IOException
     */
    public static Properties loadPropertiesByFileName(String fileName) throws IOException{
        String path = PropertiesLoader.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        File f = new File(path);
        String absolutePath = f.getParent();
        absolutePath += File.separator;
        absolutePath += fileName;
        return  loadPropertiesByFilePath(absolutePath);
    }

    /**
     * 加载文件流的配置文件
     * @param is
     * @return
     * @throws IOException
     */
    private static Properties loadProperties(InputStream is) throws IOException {
        InputStreamReader isr = new InputStreamReader(is,"UTF-8");
        BufferedReader read = new BufferedReader(isr);
        Properties pro = new Properties();
        pro.load(read);
        IOUtils.closeQuietly(read);
        IOUtils.closeQuietly(isr);
        IOUtils.closeQuietly(is);
        return  pro;
    }


    public static void main(String[] args) throws IOException {
        String key = "appkey";
        String propertyName="bassrv.properties";
        System.out.println(loadPropertiesByFileName(propertyName).getProperty(key));
    }
}
